import subprocess
import time
import os
import evdev
from evdev import InputDevice, categorize, ecodes


def record_screen(output_file):
    try:
        # 使用 ffmpeg 录制屏幕
        command = [
            'ffmpeg',
            '-f', 'x11grab',
            '-r', '25',  # 帧率
            '-i', ':0.0',  # X 显示
            output_file
        ]
        return subprocess.Popen(command)
    except Exception as e:
        print(f"屏幕录制启动失败: {e}")
        return None


def record_input_events(log_file):
    processes = []
    try:
        # 查找所有输入设备
        devices = [InputDevice(path) for path in evdev.list_devices()]
        for device in devices:
            try:
                # 记录输入设备事件
                command = [
                    'evtest',
                    device.path
                ]
                with open(log_file, 'a') as f:
                    p = subprocess.Popen(command, stdout=f)
                    processes.append(p)
            except Exception as e:
                print(f"记录 {device.path} 输入事件失败: {e}")
    except Exception as e:
        print(f"查找输入设备失败: {e}")
    return processes


def main():
    # 获取当前用户名
    username = os.getenv('USER')
    # 屏幕录制文件名，包含用户名
    screen_output_file = f'screen_record_{username}.mp4'
    # 输入事件记录文件名，包含用户名
    input_log_file = f'input_events_{username}.log'

    # 开始屏幕录制
    screen_process = record_screen(screen_output_file)
    # 开始记录输入事件
    input_processes = record_input_events(input_log_file)

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        # 停止录制
        if screen_process:
            screen_process.terminate()
        for p in input_processes:
            p.terminate()
        print("录制已停止。")


if __name__ == "__main__":
    main()
    